package com.mtk.launcher.util;

import android.content.Context;
import android.os.Build;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;

import com.lark.wifi.util.MyLog;
import com.mtk.launcher.BuildConfig;

import java.lang.reflect.Method;

public class ScreenWakeUtil {

    public static ScreenWakeUtil instance;
    private Context context;
    private PowerManager powerManager;

    public static ScreenWakeUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (ScreenWakeUtil.class) {
                if (instance == null) {
                    instance = new ScreenWakeUtil(context);
                }
            }
        }
        return instance;
    }


    public ScreenWakeUtil(Context context) {
        this.context = context;
        this.powerManager = (PowerManager) this.context.getSystemService(Context.POWER_SERVICE);
    }

    /**
     * 休眠
     */
    public void gotoSleep() {
        if (BuildConfig.DEBUG) {
            return;
        }
        if (!isScreenOff()) {
            MyLog.cdl("休眠唤醒==gotoSleep==当前是暗屏->拦截操作");
            return;
        }
        MyLog.cdl("休眠唤醒==gotoSleep");
        try {
            Method method = PowerManager.class.getMethod("goToSleep", long.class);
            method.invoke(powerManager, SystemClock.uptimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 尝试唤醒屏幕（需要系统权限或 Root）
     */
    public boolean wakeUpScreen() {
        if (BuildConfig.DEBUG) {
            return true;
        }
        if (isScreenOff()) {
            MyLog.cdl("休眠唤醒==wakeUpScreen= 当前是亮屏-> 拦截操作");
            return true;
        }
        MyLog.cdl("休眠唤醒==wakeUpScreen");
        try {
            Method method;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                // Android 9.0+ 反射调用
                method = PowerManager.class.getMethod("wakeUp", long.class);
                method.invoke(powerManager, SystemClock.uptimeMillis());
            } else {
                // Android 9.0 以下版本
                method = PowerManager.class.getMethod("wakeUp", long.class, int.class, String.class);
                method.invoke(powerManager, SystemClock.uptimeMillis(), 2, "wakeUp");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean IS_SCREEN_STATE = true;

    /**
     * 检查屏幕是否关闭
     */
    private boolean isScreenOff() {
        return IS_SCREEN_STATE;
    }
}